package com.xxx.dorm.web.servlet;

import com.xxx.dorm.domain.*;
import com.xxx.dorm.service.UserService;
import com.xxx.dorm.service.impl.UserServiceImpl;
import com.xxx.dorm.utils.CookieUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public void mainIndex(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("mainRight","/WEB-INF/jsp/blank.jsp");
        request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, InvocationTargetException, IllegalAccessException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        String remember = request.getParameter("remember");//获取‘记住我’勾选框
        Users users = new Users();
        BeanUtils.populate(users,map);
        byte[] base64decodedBytes = Base64.getDecoder().decode(users.getPassword());
        users.setPassword(new String(base64decodedBytes, "utf-8"));
        Users u = userService.logins(users);
        request.getSession().setAttribute("user",u);

        if(u != null){
            //登陆成功
            if(remember != null && remember.equals("remember-me")){
                CookieUtils.addCookie("cookie_name_pass",7*24*60*60,u.getUsername(),u.getPassword(),request,response);
            }
            request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);
        }else{
            //登陆失败
            request.setAttribute("error","登陆失败！学号或者密码错误！");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }
    }

    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //销毁session
        request.getSession().removeAttribute("user");
        //清除cookie
        Cookie cookie = CookieUtils.getCookieByName("cookie_name_pass", request);
        if(cookie != null){
            cookie.setMaxAge(0);
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    public void findOldPassword(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String oldPassword = request.getParameter("oldPassword");
        Users u = userService.findOldPassword(oldPassword);
        writeValue(u,response);
    }

    public void changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String para = request.getParameter("para");
        if(para != null && "ch".equals(para)){
            request.setAttribute("mainRight","/WEB-INF/jsp/user/passwordChange.jsp");
            request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);
            return;
        }

        Users user = (Users) request.getSession().getAttribute("user");
        String password = request.getParameter("password");
        byte[] base64decodedBytes = Base64.getDecoder().decode(password);
        password = new String(base64decodedBytes, "utf-8");
        userService.updatePassword(user.getId(),password);
        //登陆失败
        request.setAttribute("error","请重新登录！");
         request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

    /**
     * 查找所有用户
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findAll(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String conditions = request.getParameter("conditions");
        String information = request.getParameter("information");
        Users user = (Users) request.getSession().getAttribute("user");
        List<Users> users = null;
        if(conditions != "" && information != "" && conditions != null && information != null){
            users = userService.find(conditions,information);
        }else{
            users = userService.findAll(user.getId());
        }
        for(int i=0;i<users.size();i++){
            Role role = userService.findByRid(users.get(i).getRid());
            users.get(i).setRole(role);
        }
        request.setAttribute("users",users);
        request.setAttribute("mainRight","/WEB-INF/jsp/user/userList.jsp");
        request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);
    }

    /**
     * 通过id查找
     */
    public void findOneUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Users users = userService.findById(id);
        Role role = userService.findByRid(users.getRid());
        users.setRole(role);
        request.setAttribute("users",users);
        request.setAttribute("mainRight","/WEB-INF/jsp/user/updateUser.jsp");
        request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);
    }

    /**
     * 添加用户
     * @param request
     * @param response
     */
    public void addUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        String para = request.getParameter("para");
        if(para != null && para.equals("add")){
            request.setAttribute("mainRight","/WEB-INF/jsp/user/addUser.jsp");
            request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);
            return;
        }
        Map<String, String[]> map = request.getParameterMap();
        Users users = new Users();
        BeanUtils.populate(users,map);
        userService.addUser(users);
        response.sendRedirect(request.getContextPath()+"/user/findAll");
    }

    /**
     * 删除用户
     * @param request
     * @param response
     */
    public void deleteUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        userService.removeUser(id);
        response.sendRedirect(request.getContextPath()+"/user/findAll");
    }

    /**
     * 修改用户
     * @param request
     * @param response
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IOException
     */
    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {

        Map<String, String[]> map = request.getParameterMap();
        Users users = new Users();
        BeanUtils.populate(users, map);
        String password = request.getParameter("passWord");
        // byte[] base64decodedBytes = Base64.getDecoder().decode(password);
        // users.setPassword(new String(base64decodedBytes, "utf-8"));
        users.setPassword(password);
        userService.updateUser(users);
        response.sendRedirect(request.getContextPath() + "/user/findAll");
    }
}
